#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Web终端服务器
提供静态文件服务和WebSocket SSH连接
"""

import os
import sys
import json
import asyncio
import logging
import threading
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
    """自定义HTTP请求处理器"""
    
    def __init__(self, *args, **kwargs):
        # 设置服务目录为当前脚本所在目录
        super().__init__(*args, directory=os.path.dirname(os.path.abspath(__file__)), **kwargs)
    
    def end_headers(self):
        # 添加CORS头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()
    
    def do_OPTIONS(self):
        """处理OPTIONS请求"""
        self.send_response(200)
        self.end_headers()
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        logger.info(f"{self.address_string()} - {format % args}")
    
    def guess_type(self, path):
        """设置正确的MIME类型"""
        mimetype, encoding = super().guess_type(path)
        
        # 确保JavaScript文件有正确的MIME类型
        if path.endswith('.js'):
            return 'application/javascript'
        elif path.endswith('.css'):
            return 'text/css'
        elif path.endswith('.html'):
            return 'text/html; charset=utf-8'
        
        return mimetype

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    """支持多线程的HTTP服务器"""
    daemon_threads = True
    allow_reuse_address = True

def check_docker_container():
    """检查Docker容器状态"""
    try:
        import subprocess
        result = subprocess.run(
            ['docker', 'ps', '--filter', 'name=linux-basic', '--format', 'table {{.Names}}\t{{.Status}}'],
            capture_output=True,
            text=True,
            timeout=10
        )
        
        if result.returncode == 0:
            lines = result.stdout.strip().split('\n')
            if len(lines) > 1:  # 有标题行和数据行
                container_info = lines[1]
                if 'Up' in container_info:
                    logger.info("✅ Linux容器正在运行")
                    return True
                else:
                    logger.warning("⚠️  Linux容器未运行")
                    return False
            else:
                logger.warning("⚠️  未找到linux-basic容器")
                return False
        else:
            logger.error(f"❌ 检查容器状态失败: {result.stderr}")
            return False
            
    except subprocess.TimeoutExpired:
        logger.error("❌ 检查容器状态超时")
        return False
    except FileNotFoundError:
        logger.error("❌ 未找到Docker命令，请确保Docker已安装")
        return False
    except Exception as e:
        logger.error(f"❌ 检查容器状态时发生错误: {e}")
        return False

def start_container():
    """启动Docker容器"""
    try:
        import subprocess
        
        # 检查docker-compose.yml是否存在
        compose_file = Path(__file__).parent.parent / 'docker-compose.yml'
        if not compose_file.exists():
            logger.error(f"❌ 未找到docker-compose.yml文件: {compose_file}")
            return False
        
        logger.info("🚀 正在启动Linux容器...")
        
        # 切换到docker-compose.yml所在目录
        cwd = compose_file.parent
        
        result = subprocess.run(
            ['docker-compose', 'up', '-d'],
            cwd=cwd,
            capture_output=True,
            text=True,
            timeout=60
        )
        
        if result.returncode == 0:
            logger.info("✅ Linux容器启动成功")
            return True
        else:
            logger.error(f"❌ 启动容器失败: {result.stderr}")
            return False
            
    except subprocess.TimeoutExpired:
        logger.error("❌ 启动容器超时")
        return False
    except FileNotFoundError:
        logger.error("❌ 未找到docker-compose命令，请确保Docker Compose已安装")
        return False
    except Exception as e:
        logger.error(f"❌ 启动容器时发生错误: {e}")
        return False

def print_banner():
    """打印启动横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════╗
║                    🖥️  Web终端服务器                          ║
║                                                              ║
║  📡 HTTP服务器已启动                                          ║
║  🌐 访问地址: http://localhost:8081                          ║
║  📁 服务目录: web-terminal/                                   ║
║                                                              ║
║  🐧 Linux容器连接信息:                                        ║
║     📍 地址: localhost:2222                                   ║
║     👤 用户: developer                                        ║
║     🔑 密码: dev123                                           ║
║                                                              ║
║  ⌨️  快捷键:                                                  ║
║     Ctrl+C - 停止服务器                                       ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
"""
    print(banner)

def main():
    """主函数"""
    # 设置服务器参数
    HOST = 'localhost'
    PORT = 8081
    
    try:
        # 检查并启动容器
        if not check_docker_container():
            logger.info("🔄 尝试启动Linux容器...")
            if not start_container():
                logger.warning("⚠️  容器启动失败，但Web服务器仍会启动")
                logger.info("💡 您可以手动启动容器: cd ../docker/linux-basic && docker-compose up -d")
        
        # 创建HTTP服务器
        server = ThreadingHTTPServer((HOST, PORT), CustomHTTPRequestHandler)
        
        print_banner()
        logger.info(f"🚀 Web终端服务器启动成功")
        logger.info(f"📡 监听地址: http://{HOST}:{PORT}")
        logger.info(f"📁 服务目录: {os.path.dirname(os.path.abspath(__file__))}")
        logger.info("")
        logger.info("🌐 请在浏览器中打开: http://localhost:8081")
        logger.info("")
        logger.info("按 Ctrl+C 停止服务器")
        
        # 启动服务器
        server.serve_forever()
        
    except KeyboardInterrupt:
        logger.info("\n🛑 收到停止信号，正在关闭服务器...")
        server.shutdown()
        server.server_close()
        logger.info("✅ 服务器已停止")
        
    except OSError as e:
        if e.errno == 10048:  # Windows: Address already in use
            logger.error(f"❌ 端口 {PORT} 已被占用，请检查是否有其他程序在使用该端口")
            logger.info("💡 您可以尝试关闭占用端口的程序，或修改server.py中的PORT变量")
        else:
            logger.error(f"❌ 网络错误: {e}")
        sys.exit(1)
        
    except Exception as e:
        logger.error(f"❌ 服务器启动失败: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()